<!DOCTYPE html>



  


<html class="theme-next mist use-motion" lang="_en">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">












<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />






















<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=6.0.2" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=6.0.2">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=6.0.2">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=6.0.2">


  <link rel="mask-icon" href="/images/logo.svg?v=6.0.2" color="#222">









<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Mist',
    version: '6.0.2',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: false,
    fastclick: false,
    lazyload: false,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>


  




  
  <meta name="keywords" content="python,numpy,pandas," />


<meta name="description" content="Note for python functions.">
<meta name="keywords" content="python,numpy,pandas">
<meta property="og:type" content="article">
<meta property="og:title" content="learn python">
<meta property="og:url" content="https://hunterMG.github.io/2018/03/26/learn-python/index.html">
<meta property="og:site_name" content="HunterMG">
<meta property="og:description" content="Note for python functions.">
<meta property="og:locale" content="_en">
<meta property="og:updated_time" content="2019-12-01T09:01:45.625Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="learn python">
<meta name="twitter:description" content="Note for python functions.">



  <link rel="alternate" href="/atom.xml" title="HunterMG" type="application/atom+xml" />




  <link rel="canonical" href="https://hunterMG.github.io/2018/03/26/learn-python/"/>


  <title>learn python | HunterMG</title>
  






  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?c29221d17e053907b4474d8c70ec318e";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>




  <noscript>
  <style type="text/css">
    .use-motion .motion-element,
    .use-motion .brand,
    .use-motion .menu-item,
    .sidebar-inner,
    .use-motion .post-block,
    .use-motion .pagination,
    .use-motion .comments,
    .use-motion .post-header,
    .use-motion .post-body,
    .use-motion .collection-title { opacity: initial; }

    .use-motion .logo,
    .use-motion .site-title,
    .use-motion .site-subtitle {
      opacity: initial;
      top: initial;
    }

    .use-motion {
      .logo-line-before i { left: initial; }
      .logo-line-after i { right: initial; }
    }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="_en">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"> <div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">HunterMG</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">Note & share</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            <i class="menu-item-icon fa fa-fw fa-home"></i> <br />Home</a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />Tags</a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            <i class="menu-item-icon fa fa-fw fa-th"></i> <br />Categories</a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />Archives</a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />Search</a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off"
             placeholder="Searching..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>


  



 </div>
    </header>

    
  
  
  
    <a href="https://github.com/hunterMG" class="github-corner" target="_blank" title="Follow me on GitHub" aria-label="Follow me on GitHub"><svg width="80" height="80" viewBox="0 0 250 250" style="fill:#222; color:#fff; position: absolute; top: 0; border: 0; right: 0;" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"></path></svg></a>



    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://hunterMG.github.io/2018/03/26/learn-python/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="hunterMG">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="HunterMG">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">learn python</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">Posted on</span>
              
              <time title="Post created" itemprop="dateCreated datePublished" datetime="2018-03-26T09:57:47+08:00">2018-03-26</time>
            

            
            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">In</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing"><a href="/categories/development/" itemprop="url" rel="index"><span itemprop="name">development</span></a></span>

                
                
              
            </span>
          

          
            
              <span class="post-comments-count">
                <span class="post-meta-divider">|</span>
                <span class="post-meta-item-icon">
                  <i class="fa fa-comment-o"></i>
                </span>
                <a href="/2018/03/26/learn-python/#comments" itemprop="discussionUrl">
                  <span class="post-comments-count disqus-comment-count"
                        data-disqus-identifier="2018/03/26/learn-python/" itemprop="commentCount"></span>
                </a>
              </span>
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>Note for python functions.<br><a id="more"></a></p>
<h2 id="Counter"><a href="#Counter" class="headerlink" title="Counter()"></a><a href="http://www.pythoner.com/205.html" target="_blank" rel="noopener">Counter()</a></h2><h2 id="most-common"><a href="#most-common" class="headerlink" title="most_common()"></a><a href="http://www.pythoner.com/205.html" target="_blank" rel="noopener">most_common()</a></h2><h1 id="Numpy"><a href="#Numpy" class="headerlink" title="Numpy"></a>Numpy</h1><h2 id="sum"><a href="#sum" class="headerlink" title="sum"></a><a href="https://docs.scipy.org/doc/numpy-1.14.0/reference/generated/numpy.sum.html#numpy.sum" target="_blank" rel="noopener">sum</a></h2><p>Calculate the summary of ndarray a according to the given axis, axis is a integer or tuple</p>
<h2 id="argsort"><a href="#argsort" class="headerlink" title="argsort"></a><a href="">argsort</a></h2><p>返回数组的排序索引（从小到大），若为矩阵可指定轴。<br><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">k = <span class="number">2</span></span><br><span class="line">x = np.array([[<span class="number">4</span>, <span class="number">5</span>, <span class="number">1</span>],</span><br><span class="line">              [<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>]])</span><br><span class="line">top_k_idx = np.argsort(x[<span class="number">0</span>])[:k]</span><br><span class="line">print(x)</span><br><span class="line">print(top_k_idx)</span><br><span class="line"></span><br><span class="line">top_k = np.argsort(x, axis=<span class="number">1</span>)</span><br><span class="line">print(top_k)</span><br></pre></td></tr></table></figure></p>
<h2 id="np-square"><a href="#np-square" class="headerlink" title="np.square"></a>np.square</h2><p><code>np.square</code>是用c实现的，比<code>**</code>快多了😭。 661s:36s.</p>
<h2 id="np-linalg-norm"><a href="#np-linalg-norm" class="headerlink" title="np.linalg.norm"></a>np.linalg.norm</h2><p>求<a href="https://blog.csdn.net/shijing_0214/article/details/51757564" target="_blank" rel="noopener">范数</a>，L1范数-&gt;曼哈顿距离（L1距离），L2范数-&gt;欧氏距离（L2距离）<a href="https://blog.csdn.net/hqh131360239/article/details/79061535" target="_blank" rel="noopener">np.linalg.norm</a></p>
<h2 id="vstack-hstack"><a href="#vstack-hstack" class="headerlink" title="vstack, hstack"></a><a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.vstack.html" target="_blank" rel="noopener">vstack, hstack</a></h2><p><a href="https://blog.csdn.net/csdn15698845876/article/details/73380803" target="_blank" rel="noopener">refer</a></p>
<h2 id="array-split"><a href="#array-split" class="headerlink" title="array_split"></a><a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.array_split.html" target="_blank" rel="noopener">array_split</a></h2><h2 id="concatenate"><a href="#concatenate" class="headerlink" title="concatenate"></a><a href="https://blog.csdn.net/garfielder007/article/details/51378296" target="_blank" rel="noopener">concatenate</a></h2><h2 id="np-random-choice"><a href="#np-random-choice" class="headerlink" title="np.random.choice"></a>np.random.choice</h2><p>生成随机序列，可指定范围或来源于某个数组。</p>
<h2 id="reshape"><a href="#reshape" class="headerlink" title="reshape"></a>reshape</h2><p>改变矩阵为指定形状</p>
<h2 id="mean"><a href="#mean" class="headerlink" title="mean"></a>mean</h2><p>求平均值，可指定matrix的轴</p>
<h2 id="fmax-x1-x2"><a href="#fmax-x1-x2" class="headerlink" title="fmax(x1, x2)"></a>fmax(x1, x2)</h2><p>Compare two arrays and returns a new array containing the element-wise maxima. x2可以是一个数。</p>
<h2 id="numpy-random-randn-d0-d1-…-dn"><a href="#numpy-random-randn-d0-d1-…-dn" class="headerlink" title="numpy.random.randn(d0, d1, …, dn)"></a>numpy.random.randn(d0, d1, …, dn)</h2><p>从标准正态分布中返回一个或多个样本值。</p>
<h2 id="numpy-random-rand-d0-d1-…-dn"><a href="#numpy-random-rand-d0-d1-…-dn" class="headerlink" title="numpy.random.rand(d0, d1, …, dn)"></a>numpy.random.rand(d0, d1, …, dn)</h2><p>随机样本位于[0, 1)中。</p>
<h2 id="xa0-n"><a href="#xa0-n" class="headerlink" title="\xa0 \n"></a>\xa0 \n</h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&gt;&gt;&gt; </span>s</span><br><span class="line"><span class="string">'T-shirt\xa0\xa0短袖圆领衫,体恤衫\xa0'</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>out = <span class="string">""</span>.join(s.split())</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>out</span><br><span class="line"><span class="string">'T-shirt短袖圆领衫,体恤衫'</span></span><br></pre></td></tr></table></figure>
<h2 id="list-comprehension"><a href="#list-comprehension" class="headerlink" title="list comprehension"></a><a href="https://www.pythonforbeginners.com/basics/list-comprehensions-in-python" target="_blank" rel="noopener">list comprehension</a></h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">new_list = [ expression(i) <span class="keyword">for</span> i <span class="keyword">in</span> old_list <span class="keyword">if</span> filter(i)]</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>data[<span class="number">0</span>]</span><br><span class="line">&#123;<span class="string">'votes'</span>: &#123;<span class="string">'funny'</span>: <span class="number">0</span>, <span class="string">'useful'</span>: <span class="number">5</span>, <span class="string">'cool'</span>: <span class="number">2</span>&#125;,</span><br><span class="line"> <span class="string">'user_id'</span>: <span class="string">'rLtl8ZkDX5vH5nAx9C3q5Q'</span>,</span><br><span class="line"> <span class="string">'review_id'</span>: <span class="string">'fWKvX83p0-ka4JS3dc6E5A'</span>&#125;</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>votes = pd.DataFrame([i[<span class="string">'votes'</span>] <span class="keyword">for</span> i <span class="keyword">in</span> data]) <span class="comment"># data is a list which element is dict.</span></span><br></pre></td></tr></table></figure>
<h2 id="np-random-shuffle"><a href="#np-random-shuffle" class="headerlink" title="np.random.shuffle()"></a>np.random.shuffle()</h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">In [<span class="number">26</span>]: x = np.arange(<span class="number">10</span>)</span><br><span class="line"></span><br><span class="line">In [<span class="number">27</span>]: x</span><br><span class="line">Out[<span class="number">27</span>]: array([<span class="number">0</span>, <span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="number">4</span>, <span class="number">5</span>, <span class="number">6</span>, <span class="number">7</span>, <span class="number">8</span>, <span class="number">9</span>])</span><br><span class="line"></span><br><span class="line">In [<span class="number">28</span>]: np.random.shuffle(x)</span><br><span class="line"></span><br><span class="line">In [<span class="number">29</span>]: x</span><br><span class="line">Out[<span class="number">29</span>]: array([<span class="number">8</span>, <span class="number">3</span>, <span class="number">4</span>, <span class="number">7</span>, <span class="number">9</span>, <span class="number">5</span>, <span class="number">1</span>, <span class="number">6</span>, <span class="number">0</span>, <span class="number">2</span>])</span><br></pre></td></tr></table></figure>
<h2 id="pandas-Dataframe-get-rows-by-index-array"><a href="#pandas-Dataframe-get-rows-by-index-array" class="headerlink" title="pandas Dataframe get rows by index array"></a>pandas Dataframe get rows by index array</h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">split_data</span><span class="params">(data)</span>:</span></span><br><span class="line">    x_num = data.shape[<span class="number">0</span>]</span><br><span class="line">    x_idx = np.arange(x_num)</span><br><span class="line">    np.random.shuffle(x_idx)</span><br><span class="line">    x_idx_train = x_idx[<span class="number">0</span> : int(x_num*<span class="number">0.7</span>)]</span><br><span class="line">    x_idx_test = x_idx[int(x_num*<span class="number">0.7</span>) : ]</span><br><span class="line">    train = data.iloc[x_idx_train]</span><br><span class="line">    test = data.iloc[x_idx_test]</span><br><span class="line">    <span class="keyword">return</span> train, test</span><br></pre></td></tr></table></figure>
<h2 id="str-clean"><a href="#str-clean" class="headerlink" title="str clean"></a>str clean</h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">str1 = <span class="string">''</span>.join(str1.split()) <span class="comment"># remove '\n','\xa0'</span></span><br></pre></td></tr></table></figure>
<h2 id="pandas-add-a-column-to-a-Daraframe"><a href="#pandas-add-a-column-to-a-Daraframe" class="headerlink" title="pandas : add a column to a Daraframe"></a>pandas : add a column to a Daraframe</h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">data_df[<span class="string">'cool'</span>] = votes[<span class="string">'cool'</span>]</span><br></pre></td></tr></table></figure>
<h2 id="pandas-groupby-mean"><a href="#pandas-groupby-mean" class="headerlink" title="pandas : groupby mean"></a>pandas : groupby mean</h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">data_df.groupby(<span class="string">'stars'</span>).mean()</span><br></pre></td></tr></table></figure>
<h2 id="pandas-group-and-count-unique-values"><a href="#pandas-group-and-count-unique-values" class="headerlink" title="pandas : group and count unique values"></a>pandas : group and count unique values</h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">srcIp_Host_count = df.groupby(by=<span class="string">'srcIp'</span>)[<span class="string">'requestHost'</span>].nunique()</span><br></pre></td></tr></table></figure>
<h2 id="pandas-：SettingwithCopyWarning"><a href="#pandas-：SettingwithCopyWarning" class="headerlink" title="pandas ：SettingwithCopyWarning"></a><a href="https://www.jianshu.com/p/72274ccb647a" target="_blank" rel="noopener">pandas ：SettingwithCopyWarning</a></h2><h2 id="pandas-reindex-，-reset-index"><a href="#pandas-reindex-，-reset-index" class="headerlink" title="pandas : reindex() ， reset_index()"></a>pandas : reindex() ， reset_index()</h2><p>reindex() 是取出index为参数中指定的行<br>reset_index() 才是重置索引</p>
<h2 id="pandas-apply-也可用做遍历df的操作"><a href="#pandas-apply-也可用做遍历df的操作" class="headerlink" title="[pandas : apply 也可用做遍历df的操作]"></a>[pandas : apply 也可用做遍历df的操作]</h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> re</span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">clear_character</span><span class="params">(item)</span>:</span></span><br><span class="line">    <span class="string">'''去掉所有非中文字符'''</span></span><br><span class="line">    pattern1=<span class="string">'[a-zA-Z0-9]'</span></span><br><span class="line">    pattern2 = <span class="string">'\[.*?\]'</span></span><br><span class="line">    pattern3 = re.compile(<span class="string">u'[^\s1234567890:：'</span> + <span class="string">'\u4e00-\u9fa5]+'</span>)</span><br><span class="line">    pattern4=<span class="string">'[’!"#$%&amp;\'()*+,-./:;&lt;=&gt;?@[\\]^_`&#123;|&#125;~]+'</span></span><br><span class="line">    <span class="keyword">if</span> len(item[<span class="string">'content'</span>]) == <span class="number">0</span>:</span><br><span class="line">        item[<span class="string">'content'</span>] = item[<span class="string">'title'</span>]</span><br><span class="line">    line1=re.sub(pattern1,<span class="string">''</span>,item[<span class="string">'content'</span>])   <span class="comment">#去除英文字母和数字</span></span><br><span class="line">    line2=re.sub(pattern2,<span class="string">''</span>,line1)   <span class="comment">#去除表情</span></span><br><span class="line">    line3=re.sub(pattern3,<span class="string">''</span>,line2)   <span class="comment">#去除其它字符</span></span><br><span class="line">    line4=re.sub(pattern4, <span class="string">''</span>, line3) <span class="comment">#去掉残留的冒号及其它符号</span></span><br><span class="line">    item[<span class="string">'content'</span>]=<span class="string">''</span>.join(line4.split()) <span class="comment">#去除空白</span></span><br><span class="line">    <span class="keyword">return</span> item</span><br><span class="line"></span><br><span class="line">data = data.apply(clear_character, axis=<span class="number">1</span>)</span><br></pre></td></tr></table></figure>
<h2 id="jupyter-允许外网访问"><a href="#jupyter-允许外网访问" class="headerlink" title="jupyter 允许外网访问"></a>jupyter 允许外网访问</h2><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">jupyter notebook --ip=&lt;host_ip&gt;</span><br></pre></td></tr></table></figure>
      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/python/" rel="tag"># python</a>
          
            <a href="/tags/numpy/" rel="tag"># numpy</a>
          
            <a href="/tags/pandas/" rel="tag"># pandas</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2018/03/22/python-import-errors-notes/" rel="next" title="python errors notes">
                <i class="fa fa-chevron-left"></i> python errors notes
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2018/04/11/Hackintosh-note/" rel="prev" title="Hackintosh note">
                Hackintosh note <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          

  
    <div class="comments" id="comments">
      <div id="disqus_thread">
        <noscript>
          Please enable JavaScript to view the
          <a href="https://disqus.com/?ref_noscript">comments powered by Disqus.</a>
        </noscript>
      </div>
    </div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            Table of Contents
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            Overview
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <p class="site-author-name" itemprop="name">hunterMG</p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          
            <nav class="site-state motion-element">
              
                <div class="site-state-item site-state-posts">
                
                  <a href="/archives/">
                
                    <span class="site-state-item-count">13</span>
                    <span class="site-state-item-name">posts</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-categories">
                  <a href="/categories/index.html">
                    <span class="site-state-item-count">7</span>
                    <span class="site-state-item-name">categories</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-tags">
                  <a href="/tags/index.html">
                    <span class="site-state-item-count">23</span>
                    <span class="site-state-item-name">tags</span>
                  </a>
                </div>
              
            </nav>
          

          
            <div class="feed-link motion-element">
              <a href="/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://github.com/hunterMG" target="_blank" title="GitHub">
                      
                        <i class="fa fa-fw fa-github"></i>GitHub</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="mailto:yanguang666@gmail.com" target="_blank" title="E-Mail">
                      
                        <i class="fa fa-fw fa-envelope"></i>E-Mail</a>
                  </span>
                
            </div>
          

          
          

          
          

          
            
          
          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#Counter"><span class="nav-number">1.</span> <span class="nav-text">Counter()</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#most-common"><span class="nav-number">2.</span> <span class="nav-text">most_common()</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#Numpy"><span class="nav-number"></span> <span class="nav-text">Numpy</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#sum"><span class="nav-number">1.</span> <span class="nav-text">sum</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#argsort"><span class="nav-number">2.</span> <span class="nav-text">argsort</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#np-square"><span class="nav-number">3.</span> <span class="nav-text">np.square</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#np-linalg-norm"><span class="nav-number">4.</span> <span class="nav-text">np.linalg.norm</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#vstack-hstack"><span class="nav-number">5.</span> <span class="nav-text">vstack, hstack</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#array-split"><span class="nav-number">6.</span> <span class="nav-text">array_split</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#concatenate"><span class="nav-number">7.</span> <span class="nav-text">concatenate</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#np-random-choice"><span class="nav-number">8.</span> <span class="nav-text">np.random.choice</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#reshape"><span class="nav-number">9.</span> <span class="nav-text">reshape</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#mean"><span class="nav-number">10.</span> <span class="nav-text">mean</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#fmax-x1-x2"><span class="nav-number">11.</span> <span class="nav-text">fmax(x1, x2)</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#numpy-random-randn-d0-d1-…-dn"><span class="nav-number">12.</span> <span class="nav-text">numpy.random.randn(d0, d1, …, dn)</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#numpy-random-rand-d0-d1-…-dn"><span class="nav-number">13.</span> <span class="nav-text">numpy.random.rand(d0, d1, …, dn)</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#xa0-n"><span class="nav-number">14.</span> <span class="nav-text">\xa0 \n</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#list-comprehension"><span class="nav-number">15.</span> <span class="nav-text">list comprehension</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#np-random-shuffle"><span class="nav-number">16.</span> <span class="nav-text">np.random.shuffle()</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#pandas-Dataframe-get-rows-by-index-array"><span class="nav-number">17.</span> <span class="nav-text">pandas Dataframe get rows by index array</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#str-clean"><span class="nav-number">18.</span> <span class="nav-text">str clean</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#pandas-add-a-column-to-a-Daraframe"><span class="nav-number">19.</span> <span class="nav-text">pandas : add a column to a Daraframe</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#pandas-groupby-mean"><span class="nav-number">20.</span> <span class="nav-text">pandas : groupby mean</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#pandas-group-and-count-unique-values"><span class="nav-number">21.</span> <span class="nav-text">pandas : group and count unique values</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#pandas-：SettingwithCopyWarning"><span class="nav-number">22.</span> <span class="nav-text">pandas ：SettingwithCopyWarning</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#pandas-reindex-，-reset-index"><span class="nav-number">23.</span> <span class="nav-text">pandas : reindex() ， reset_index()</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#pandas-apply-也可用做遍历df的操作"><span class="nav-number">24.</span> <span class="nav-text">[pandas : apply 也可用做遍历df的操作]</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#jupyter-允许外网访问"><span class="nav-number">25.</span> <span class="nav-text">jupyter 允许外网访问</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; 2017 &mdash; <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">hunterMG</span>

  

  
</div>




  <div class="powered-by">Powered by <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a></div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">Theme &mdash; <a class="theme-link" target="_blank" href="https://github.com/theme-next/hexo-theme-next">NexT.Mist</a> v6.0.2

  

  </div>




        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>


























  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=6.0.2"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=6.0.2"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=6.0.2"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=6.0.2"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=6.0.2"></script>



  

  
    <script id="dsq-count-scr" src="https://ygdays.disqus.com/count.js" async></script>
  

  
    <script type="text/javascript">
      var disqus_config = function () {
        this.page.url = 'https://hunterMG.github.io/2018/03/26/learn-python/';
        this.page.identifier = '2018/03/26/learn-python/';
        this.page.title = 'learn python';
      };
      function loadComments () {
        var d = document, s = d.createElement('script');
        s.src = 'https://ygdays.disqus.com/embed.js';
        s.setAttribute('data-timestamp', '' + +new Date());
        (d.head || d.body).appendChild(s);
      }
      
        loadComments();
      
    </script>
  





	





  












  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  

  
  

  

  

  

  

</body>
</html>
